const uploadForm = document.getElementById('uploadForm');
const imageInput = document.getElementById('imageInput');
const chooseImageButton = document.getElementById('chooseImageButton');
const imagePreview = document.getElementById('imagePreview');
const resultDiv = document.getElementById('result');

chooseImageButton.addEventListener('click', () => {
    imageInput.click(); // 触发文件输入元素的点击事件
});

imageInput.addEventListener('change', () => {
    const file = imageInput.files[0];
    if (file) {
        const reader = new FileReader();
        reader.onload = function(event) {
            imagePreview.innerHTML = `<img src="${event.target.result}" alt="预览图" style="max-width: 100%;">`;
        };
        reader.readAsDataURL(file);
    } else {
        imagePreview.innerHTML = '';
    }
});

uploadForm.addEventListener('submit', async (e) => {
    e.preventDefault();
    const formData = new FormData(uploadForm);
    console.log('FormData:', formData);

    try {
        const response = await fetch('http://localhost:3000/process-image', {
            method: 'POST',
            body: formData
        });
        const data = await response.json();
        displayResult(data);
    } catch (error) {
        console.error('Error:', error);
    }
});

function displayResult(rawData) {
    //后端返回的数据格式是字符串，这里转换为json数据
    const data = JSON.parse(rawData);
        if (data && data.result && Array.isArray(data.result)) {
            let output = '';
            data.result.forEach(result => {
                const name = result.name || 'Unknown';
                const score = result.score || 'N/A';
                output += `${name}：${score}<br>`;
            });
            resultDiv.innerHTML = output;
        } else {
        resultDiv.innerHTML = 'No data available.';
        }
        // if(data){
        //     resultDiv.innerHTML = 'data';
        // }
        // if(data.result){
        //     resultDiv.innerHTML = 'data.result';
        // }
        // if(Array.isArray(data.result)){
        //     resultDiv.innerHTML = 'Array.isArray(data.result)';
        //     console.log(rawData)
        //     console.log(data)
        //     console.log('1111')
            
        // }
    }

// 添加按钮点击事件监听器
document.getElementById("processImageButton").addEventListener("click", function() {
    // 发送 AJAX 请求到后端路由
    fetch('http://localhost:3000/run-python-script')
        .then(response => response.text())
        .then(data => {
            // 显示返回的数据在页面上
            displayText(data);
        })
        .catch(error => {
            console.error('Error:', error);
            // 在页面上显示错误消息
            document.getElementById("result").innerHTML = 'Error occurred while processing image.';
        });
});

// 显示处理结果的函数
function displayText(data) {
        // 将原始数据直接显示在页面上
        document.getElementById("result").innerHTML = data;
    }

